# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" test_training """

import os
import numpy as np
from sklearn.metrics import roc_auc_score
import mindspore
import mindspore.common.dtype as mstype
from mindspore.ops import functional as F
from mindspore.ops import composite as C
from mindspore.ops import operations as P
from mindspore.nn import Dropout
from mindspore.nn.optim import Adam
from mindspore.nn.metrics import Metric
from mindspore import nn, Tensor, ParameterTuple, Parameter
from mindspore.common.initializer import Uniform, initializer
from mindspore.train.callback import ModelCheckpoint, CheckpointConfig
from mindspore.context import ParallelMode, get_auto_parallel_context
from mindspore.communication.management import get_group_size
from mindspore.nn.wrap.grad_reducer import DistributedGradReducer

from src.callback import EvalCallBack, LossCallBack

np_type = np.float32
ms_type = mstype.float32

class AUCMetric(Metric):
    """
    Metric method
    """
    def __init__(self):
        super(AUCMetric, self).__init__()
        self.pred_probs = []
        self.true_labels = []

    def clear(self):
        """Clear the internal evaluation result."""
        self.pred_probs = []
        self.true_labels = []

    def update(self, *inputs):
        batch_predict = inputs[1].asnumpy()
        batch_label = inputs[2].asnumpy()
        self.pred_probs.extend(batch_predict.flatten().tolist())
        self.true_labels.extend(batch_label.flatten().tolist())

    def eval(self):
        if len(self.true_labels) != len(self.pred_probs):
            raise RuntimeError('true_labels.size() is not equal to pred_probs.size()')
        auc = roc_auc_score(self.true_labels, self.pred_probs)
        return auc



class FeaturesLinear(mindspore.nn.Cell):

    def __init__(self, field_dims, output_dim=1):
        super().__init__()

        self.zeros =  P.Zeros()
        self.fc = mindspore.nn.Embedding(int(sum(field_dims)), output_dim,dtype=mstype.int32)          #sum(field_dims)

        self.bias = mindspore.Parameter(self.zeros((output_dim,), mindspore.float32))   #mindspore.ops.Zeros((output_dim,))     
        self.offsets = np.array((0, *np.cumsum(field_dims)[:-1]), dtype=np.long)

    def construct(self, x):
        """
        :param x: Long tensor of size ``(batch_size, num_fields)``
        """
        offsets = mindspore.ops.Reshape()(Tensor(self.offsets),(1,x.shape[1]))


        x = x + offsets
        x = x.astype(mindspore.int32)
        
        
        return mindspore.ops.ReduceSum()(self.fc(x), 1) + self.bias

class FeaturesEmbedding(mindspore.nn.Cell):

    def __init__(self, field_dims, embed_dim):
        super().__init__()
        self.embedding = mindspore.nn.Embedding(int(sum(field_dims)), embed_dim, embedding_table='uniform')
        self.offsets = np.array((0, *np.cumsum(field_dims)[:-1]), dtype=np.long)


    def construct(self, x):
        """
        :param x: Long tensor of size ``(batch_size, num_fields)``
        """
        offsets = mindspore.ops.Reshape()(Tensor(self.offsets),(1,x.shape[1]))
        x = x + offsets
        x = x.astype(mindspore.int32)
        return self.embedding(x)

class FactorizationMachine(mindspore.nn.Cell):

    def __init__(self, reduce_sum=True):
        super().__init__()
        self.reduce_sum = reduce_sum

    def construct(self, x):
        """
        :param x: Float tensor of size ``(batch_size, num_fields, embed_dim)``
        """
        square_of_sum = mindspore.ops.ReduceSum()(x, 1) ** 2
        sum_of_square = mindspore.ops.ReduceSum()(x ** 2, 1)
        ix = square_of_sum - sum_of_square
        if self.reduce_sum:
            ix = mindspore.ops.ReduceSum( keep_dims=True)(ix, 1)
        return 0.5 * ix

class FactorizationMachineModel(mindspore.nn.Cell):

    def __init__(self, config):
        super().__init__()
        field_dims = config.field_dims 
        embed_dim = config.embed_dim
        self.embedding = FeaturesEmbedding(field_dims, embed_dim)
        self.linear = FeaturesLinear(field_dims)
        self.fm = FactorizationMachine(reduce_sum=True)

    def construct(self, x):
        """
        :param x: Long tensor of size ``(batch_size, num_fields)``
        """
        x = self.linear(x) + self.fm(self.embedding(x))
        return mindspore.ops.Sigmoid()(x.squeeze(1)) 


class NetWithLossClass(nn.Cell):
    """
    NetWithLossClass definition
    """
    def __init__(self, network, l2_coef=1e-6):
        super(NetWithLossClass, self).__init__(auto_prefix=False)
        #self.loss = P.SigmoidCrossEntropyWithLogits()
        self.loss = mindspore.nn.BCELoss( reduction='mean')  ###
        self.network = network

    def construct(self, x, label):  #(self, x label)

        predict = self.network(x) 

        predict = mindspore.ops.ExpandDims()(predict,1)
        
        loss = self.loss(predict, label)
        return loss

class TrainStepWrap(nn.Cell):
    """
    TrainStepWrap definition 
    """
    def __init__(self, network, lr, eps, loss_scale=1000.0,weight_decay = 0.0):
        super(TrainStepWrap, self).__init__(auto_prefix=False)
        self.network = network
        self.network.set_train()
        self.weights = ParameterTuple(network.trainable_params())
        self.optimizer = Adam(self.weights, learning_rate=lr, eps=eps, loss_scale=loss_scale,weight_decay = weight_decay)
        self.hyper_map = C.HyperMap()
        self.grad = C.GradOperation(get_by_list=True, sens_param=True)
        self.sens = loss_scale

        self.reducer_flag = False
        self.grad_reducer = None
        parallel_mode = get_auto_parallel_context("parallel_mode")
        if parallel_mode in (ParallelMode.DATA_PARALLEL, ParallelMode.HYBRID_PARALLEL):
            self.reducer_flag = True
        if self.reducer_flag:
            mean = get_auto_parallel_context("gradients_mean")
            degree = get_group_size()
            self.grad_reducer = DistributedGradReducer(self.optimizer.parameters, mean, degree)

    def construct(self, x, label): 
        weights = self.weights
        loss = self.network(x, label)
        sens = P.Fill()(P.DType()(loss), P.Shape()(loss), self.sens) #
        grads = self.grad(self.network, weights)(x, label, sens)

        if self.reducer_flag:
            # apply grad reducer on grads
            grads = self.grad_reducer(grads)
        return F.depend(loss, self.optimizer(grads))

class PredictWithSigmoid(nn.Cell):
    """
    Predict method
    """
    def __init__(self, network):
        super(PredictWithSigmoid, self).__init__(auto_prefix=False)
        self.network = network
        self.sigmoid = P.Sigmoid()

    def construct(self, x, labels):     #(self, batch_ids, batch_wts, labels)
        logits = self.network(x)        #logits, _, _, = 
        pred_probs = self.sigmoid(logits)

        return logits, pred_probs, labels

class ModelBuilder():
    """
    Model builder for DeepFM.

    Args:
        model_config (ModelConfig): Model configuration.
        train_config (TrainConfig): Train configuration.
    """
    def __init__(self, model_config, train_config):
        self.model_config = model_config
        self.train_config = train_config

    def get_callback_list(self, model=None, eval_dataset=None):
        """
        Get callbacks which contains checkpoint callback, eval callback and loss callback.

        Args:
            model (Cell): The network is added callback (default=None)
            eval_dataset (Dataset): Dataset for eval (default=None)
        """
        callback_list = []
        if self.train_config.save_checkpoint:
            config_ck = CheckpointConfig(save_checkpoint_steps=self.train_config.save_checkpoint_steps,
                                         keep_checkpoint_max=self.train_config.keep_checkpoint_max)
            ckpt_cb = ModelCheckpoint(prefix=self.train_config.ckpt_file_name_prefix,
                                      directory=self.train_config.output_path,
                                      config=config_ck)
            callback_list.append(ckpt_cb)
        if self.train_config.eval_callback:
            if model is None:
                raise RuntimeError("train_config.eval_callback is {}; get_callback_list() args model is {}".format(
                                        self.train_config.eval_callback, model))
            if eval_dataset is None:
                raise RuntimeError("train_config.eval_callback is {}; get_callback_list() args eval_dataset is {}".
                                   format(self.train_config.eval_callback, eval_dataset))
            auc_metric = AUCMetric()
            eval_callback = EvalCallBack(model, eval_dataset, auc_metric,
                                         eval_file_path=os.path.join(self.train_config.output_path,
                                                                     self.train_config.eval_file_name))
            callback_list.append(eval_callback)
        if self.train_config.loss_callback:
            loss_callback = LossCallBack(loss_file_path=os.path.join(self.train_config.output_path,
                                                                     self.train_config.loss_file_name))
            callback_list.append(loss_callback)
        if callback_list:
            return callback_list

        return None

    def get_train_eval_net(self):
        fm_net = FactorizationMachineModel(self.model_config)
        loss_net = NetWithLossClass(fm_net, l2_coef=self.train_config.l2_coef)
        train_net = TrainStepWrap(loss_net, lr=self.train_config.learning_rate,
                                  eps=self.train_config.epsilon, loss_scale=self.train_config.loss_scale,weight_decay = self.train_config.weight_decay)
        eval_net = PredictWithSigmoid(fm_net)
        return train_net, eval_net
